﻿Imports System.Linq
Public Class fConfigUtilizadores
    Public dbMain As New LinqMainDataContext
    Public dbMenu As New MenuLinqDataContext


    Private Sub fConfigUtilizadores_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'DsAdminitracao1.tblUserConfig' table. You can move, or remove it, as needed.
        Me.TblUserConfigTableAdapter.Fill(Me.DsAdminitracao1.tblUserConfig)
        'TODO: This line of code loads data into the 'DsAdminitracao1.tblGruposAcessoDesc' table. You can move, or remove it, as needed.
        Me.TblGruposAcessoDescTableAdapter.Fill(Me.DsAdminitracao1.tblGruposAcessoDesc)



        'Carregar lista de empresas checkbox
        Dim empresas = (From c In dbMain.tblEmpresa1s _
                      Select c)
        Dim i As Integer = 0
        For Each Emp In empresas
            Dim a As New DevExpress.XtraEditors.CheckedListBoxControl
            CheckedListBoxControl1.Items.Add(a)
            CheckedListBoxControl1.Items.Item(i).Description = Emp.EmpresaDesc.ToString
            CheckedListBoxControl1.Items.Item(i).Value = Emp.Empresa.ToString
            i = i + 1
        Next
    End Sub

    Private Sub GridView1_DoubleClick(sender As Object, e As EventArgs) Handles GridView1.DoubleClick
        Dim countlist As Integer = CheckedListBoxControl1.Items.Count.ToString
        Dim ilist As Integer = 0
        Do While ilist < countlist
            CheckedListBoxControl1.Items.Item(ilist).CheckState = CheckState.Unchecked
            ilist = ilist + 1
        Loop
        Dim primeironome As String
        Dim ultimonome As String
        Dim username As String
        Dim pass As String
        Dim email As String
        Dim empresadefault As String
        Dim GrupoAcesso As String

        Dim user = (From c In dbMain.tblUsers Join o In dbMain.tblUserGrpMaps On c.UserName Equals o.UserId _
                   Where c.UserName = GridView1.GetFocusedRowCellValue(colUserName).ToString _
                   Select c, o).SingleOrDefault

        primeironome = user.c.PrimeiroNome.ToString
        ultimonome = user.c.UltimoNome.ToString
        username = user.c.UserName.ToString
        pass = user.c.Pass.ToString
        email = user.c.Email.ToString
        empresadefault = user.c.EmpresaDefault.ToString
        GrupoAcesso = user.o.GroupCode.ToString

        txtPrimeiroNome.Text = primeironome
        txtUltimoNome.Text = ultimonome
        txtEmail.Text = email
        txtUserName.Text = username
        txtPass.Text = pass
        lkGrupoCode.EditValue = GrupoAcesso
        cbEmpresaDefault.Text = empresadefault

        Dim empresas = (From c In dbMenu.tblUserEMpresas Join o In dbMenu.tblEmpresas On c.empresa Equals o.Empresa _
                   Where c.username = username _
                   Select o.EmpresaDesc)
        Dim count As Integer = CheckedListBoxControl1.Items.Count.ToString
        Dim i As Integer = 0
        Do While i < count
            For Each emp In empresas
                If CheckedListBoxControl1.Items.Item(i).Description.ToString = emp.ToString Then
                    CheckedListBoxControl1.Items.Item(i).CheckState = CheckState.Checked
                End If
            Next
            i = i + 1
        Loop
        BtnEditarUtilizador.Enabled = True
        BtnApagarUtilizador.Enabled = True
    End Sub

    Private Sub BtnNovoUtilizador_Click(sender As Object, e As EventArgs) Handles BtnNovoUtilizador.Click
        BtnNovoUtilizador.Visible = False
        BtnEditarUtilizador.Visible = False
        BtnApagarUtilizador.Visible = False
        btnGuardar.Visible = True
        btnCancelar.Visible = True
        ClearCampos(Me.SplitContainerControl1.Panel1)
        ActivarCampos(Me.SplitContainerControl1.Panel1)

    End Sub

    Private Function ClearCampos(parent As Control)
        For Each c As Control In parent.Controls

            If TypeOf c Is DevExpress.XtraEditors.TextEdit Then
                ' MessageBox.Show(c.GetType.ToString)
                DirectCast(c, DevExpress.XtraEditors.TextEdit).Text = ""
            ElseIf TypeOf c Is DevExpress.XtraEditors.LookUpEdit Then
                DirectCast(c, DevExpress.XtraEditors.LookUpEdit).Text = ""
            ElseIf TypeOf c Is CheckBox Then
                DirectCast(c, CheckBox).Checked = False
            ElseIf TypeOf c Is DevExpress.XtraEditors.RadioGroup Then
                DirectCast(c, DevExpress.XtraEditors.RadioGroup).Properties.Items.Clear()
            End If
        Next
    End Function
    Private Function ActivarCampos(parent As Control)
        For Each c As Control In parent.Controls
            If TypeOf c Is DevExpress.XtraEditors.TextEdit Then
                DirectCast(c, DevExpress.XtraEditors.TextEdit).Enabled = True
            ElseIf TypeOf c Is DevExpress.XtraEditors.CheckedListBoxControl Then
                DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).Enabled = True
                DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).UnCheckAll()
            End If
        Next
    End Function
    Private Function DesactivarCampos(parent As Control)
        For Each c As Control In parent.Controls
            If TypeOf c Is DevExpress.XtraEditors.TextEdit Then
                DirectCast(c, DevExpress.XtraEditors.TextEdit).Enabled = False
            ElseIf TypeOf c Is DevExpress.XtraEditors.CheckedListBoxControl Then
                DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).Enabled = False
                DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).UnCheckAll()
            End If
        Next
    End Function
    Private Function ValidarNovoUtilizador()
        Dim erros As Integer = 0
        Dim user = (From c In dbMain.tblUsers _
                  Where c.UserName = txtUserName.Text _
                  Select c).Count

        If user.ToString > 0 Then
            MessageBox.Show("O utilizador " & txtUserName.Text.ToString & " já existe", "Erro Utilizador", MessageBoxButtons.OK, MessageBoxIcon.Error)
            txtUserName.Focus()
            txtUserName.BackColor = Color.Tomato
            erros = erros + 1
        Else
            For Each c As Control In Me.SplitContainerControl1.Panel1.Controls
                If TypeOf c Is DevExpress.XtraEditors.TextEdit Then
                    If c.Text = String.Empty Then
                        c.BackColor = Color.Tomato
                        erros = erros + 1
                    Else
                        c.BackColor = Color.White
                    End If

                ElseIf TypeOf c Is DevExpress.XtraEditors.CheckedListBoxControl Then
                    If DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).CheckedItemsCount = 0 Then
                        DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).BackColor = Color.Tomato
                        erros = erros + 1
                    Else
                        DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).BackColor = Color.White
                    End If
                End If
            Next

        End If
        If erros = 0 Then
            GuardarUtilizador()
        End If

    End Function
    Private Function GuardarUtilizador()
        Dim user As New tblUser With _
{.UserName = txtUserName.Text, .PrimeiroNome = txtPrimeiroNome.Text, .UltimoNome = txtUltimoNome.Text, .Pass = txtPass.Text, .Email = txtEmail.Text, .EmpresaDefault = cbEmpresaDefault.Text}
        dbMain.tblUsers.InsertOnSubmit(user)

        dbMain.SubmitChanges()

        Dim grupo = New tblUserGrpMap With _
            {.UserId = txtUserName.Text, .GroupCode = lkGrupoCode.Text}
        dbMain.tblUserGrpMaps.InsertOnSubmit(grupo)



        For Each c In CheckedListBoxControl1.CheckedItems
            Dim codempresa = (From a In dbMenu.tblEmpresas _
                             Where a.EmpresaDesc = c.ToString _
                             Select a.Empresa).SingleOrDefault

            Dim empresas = New tblUserEMpresa With _
            {.username = txtUserName.Text, .empresa = codempresa.ToString}
            dbMenu.tblUserEMpresas.InsertOnSubmit(empresas)
            dbMenu.SubmitChanges()
        Next


        dbMain.SubmitChanges()

        Me.TblUserConfigTableAdapter.Fill(Me.DsAdminitracao1.tblUserConfig)

        btnGuardar.Visible = False
        btnCancelar.Visible = False
        BtnApagarUtilizador.Visible = True
        BtnEditarUtilizador.Visible = True
        BtnNovoUtilizador.Visible = True
        ClearCampos(Me.SplitContainerControl1.Panel1)
        DesactivarCampos(Me.SplitContainerControl1.Panel1)
    End Function

    Private Sub btnGuardar_Click(sender As Object, e As EventArgs) Handles btnGuardar.Click
        ValidarNovoUtilizador()

    End Sub

    Private Sub CheckedListBoxControl1_ItemCheck(sender As Object, e As DevExpress.XtraEditors.Controls.ItemCheckEventArgs) Handles CheckedListBoxControl1.ItemCheck
        If e.State = CheckState.Checked Then
            cbEmpresaDefault.Properties.Items.Add(CheckedListBoxControl1.Items.Item(e.Index).Description.ToString)
        ElseIf e.State = CheckState.Unchecked Then
            cbEmpresaDefault.Text = String.Empty
            cbEmpresaDefault.Properties.Items.Remove(CheckedListBoxControl1.Items.Item(e.Index).Description.ToString)
        End If

    End Sub

    Private Sub btnCancelar_Click(sender As Object, e As EventArgs) Handles btnCancelar.Click
        btnGuardar.Visible = False
        btnCancelar.Visible = False
        BtnApagarUtilizador.Visible = True
        BtnEditarUtilizador.Visible = True
        BtnNovoUtilizador.Visible = True
        btnGuardarEdit.Visible = False
        ClearCampos(Me.SplitContainerControl1.Panel1)
        DesactivarCampos(Me.SplitContainerControl1.Panel1)
    End Sub

    Private Sub BtnEditarUtilizador_Click(sender As Object, e As EventArgs) Handles BtnEditarUtilizador.Click
        BtnNovoUtilizador.Visible = False
        btnCancelar.Visible = True
        btnGuardarEdit.Visible = True
        BtnEditarUtilizador.Visible = False
        ActivarCamposEdit(Me.SplitContainerControl1.Panel1)
    End Sub
    Private Function ActivarCamposEdit(parent As Control)
        For Each c As Control In parent.Controls
            If TypeOf c Is DevExpress.XtraEditors.TextEdit Then
                DirectCast(c, DevExpress.XtraEditors.TextEdit).Enabled = True
            ElseIf TypeOf c Is DevExpress.XtraEditors.CheckedListBoxControl Then
                DirectCast(c, DevExpress.XtraEditors.CheckedListBoxControl).Enabled = True
            End If
        Next
    End Function

    Private Function ApagarUtilizador(username As String)
        Dim user = (From c In dbMain.tblUsers _
                  Where c.UserName = username _
                  Select c).SingleOrDefault
        dbMain.tblUsers.DeleteOnSubmit(user)

        Dim Grupo = (From c In dbMain.tblUserGrpMaps _
                    Where c.UserId = username _
                    Select c).SingleOrDefault
        dbMain.tblUserGrpMaps.DeleteOnSubmit(Grupo)

        Dim empresas = (From c In dbMenu.tblUserEMpresas _
                       Where c.username = username _
                       Select c)
        For Each empresa In empresas
            dbMenu.tblUserEMpresas.DeleteOnSubmit(empresa)
            dbMenu.SubmitChanges()
        Next

        dbMain.SubmitChanges()


    End Function

    Private Sub BtnApagarUtilizador_Click(sender As Object, e As EventArgs) Handles BtnApagarUtilizador.Click
        Dim result = MessageBox.Show("Deseja eliminar o utilizador " & txtPrimeiroNome.Text & " " & txtUltimoNome.Text & "?", "Eliminar utilizador", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = Windows.Forms.DialogResult.Yes Then
            ApagarUtilizador(txtUserName.Text)
            Me.TblUserConfigTableAdapter.Fill(Me.DsAdminitracao1.tblUserConfig)
            ClearCampos(Me.SplitContainerControl1.Panel1)
        ElseIf result = Windows.Forms.DialogResult.No Then
        End If
    End Sub

    Private Sub btnGuardarEdit_Click(sender As Object, e As EventArgs) Handles btnGuardarEdit.Click
        Dim user = (From c In dbMain.tblUsers _
                   Where c.UserName = txtUserName.Text _
                   Select c).SingleOrDefault
        With user
            .Email = txtEmail.Text
            .EmpresaDefault = cbEmpresaDefault.Text
            .Pass = txtPass.Text
            .PrimeiroNome = txtPrimeiroNome.Text
            .UltimoNome = txtUltimoNome.Text
        End With


        Dim grupo = (From c In dbMain.tblUserGrpMaps _
                    Where c.UserId = txtUserName.Text _
                    Select c).SingleOrDefault
        grupo.GroupCode = lkGrupoCode.Text

        Dim empresas = (From c In dbMenu.tblUserEMpresas _
                       Where c.username = txtUserName.Text _
                       Select c)
        For Each empresa In empresas
            dbMenu.tblUserEMpresas.DeleteOnSubmit(empresa)
            dbMenu.SubmitChanges()
        Next

        For Each c In CheckedListBoxControl1.CheckedItems
            Dim codempresa = (From a In dbMenu.tblEmpresas _
                             Where a.EmpresaDesc = c.ToString _
                             Select a.Empresa).SingleOrDefault

            Dim empresasadd = New tblUserEMpresa With _
            {.username = txtUserName.Text, .empresa = codempresa.ToString}
            dbMenu.tblUserEMpresas.InsertOnSubmit(empresasadd)
            dbMenu.SubmitChanges()
        Next

        dbMain.SubmitChanges()

        Me.TblUserConfigTableAdapter.Fill(Me.DsAdminitracao1.tblUserConfig)
        btnGuardarEdit.Visible = False
        btnGuardar.Visible = False
        btnCancelar.Visible = False
        BtnApagarUtilizador.Visible = True
        BtnEditarUtilizador.Visible = True
        BtnEditarUtilizador.Enabled = False
        BtnApagarUtilizador.Enabled = False
        BtnNovoUtilizador.Visible = True
        ClearCampos(Me.SplitContainerControl1.Panel1)
        DesactivarCampos(Me.SplitContainerControl1.Panel1)
    End Sub
End Class